import { Daemon } from 'ipfs-daemon';
import { multiaddrToUri } from '@multiformats/multiaddr-to-uri';

import { seedHexToPriveKey } from './peer-id.js';

import dotenv from 'dotenv'
import Logger from 'logplease'

import events from 'events'
events.EventEmitter.defaultMaxListeners = 0

const logger = Logger.create('relay')
Logger.setLogLevel('DEBUG')

dotenv.config()
// logger.debug(process.env)

const SEED_HEX = '5110e63bf075b89770deb88d89281526d5c858380e76db257a86834bb42d2085'
// 12D3KooWELrypWhpyUef9gtJr5TUne1173fG24QpMrRN62HN4VDk

const ipfsConfig = {
  "Addresses": {
    "Swarm": [
      // "/ip4/0.0.0.0/tcp/4002",
      "/ip4/0.0.0.0/tcp/0/ws",
      // '/dns4/webrtc.we-linkin.com/tcp/443/wss/p2p-webrtc-star/',
    ],
    "Announce": [
      // '/dns4/libp.we-linkin.com/tcp/44003/wss/p2p/12D3KooWKAJRPaAXWredsghaXHprgsz1eJ4AW5msHkdXWEwNmMcR'
    ],
    "NoAnnounce": [],
    "API": "/ip4/0.0.0.0/tcp/5008",
    "Gateway": "/ip4/0.0.0.0/tcp/9098",
    "RPC": "/ip4/0.0.0.0/tcp/5009",
  },
  "API": {
    "HTTPHeaders": {
      "Access-Control-Allow-Origin": [
        "*"
      ]
    }
  },
  
};

function createDaemon(privateKey) {
  return new Daemon({
    config: ipfsConfig,
    // ipld: {
    //   formats: [
    //     dagJoseFormat
    //   ]
    // },
    silent: false,
    repo: 'jsipfs',
    repoAutoMigrate: true,
    offline: false,
    pass: undefined,
    preload: { enabled: true },
    EXPERIMENTAL: { 
      ipnsPubsub: false, sharding: false,
    },
    init: {
      privateKey
    },
  });
}

const print = (msg) => logger.debug(msg);
async function startServer() {

  const privateKey = await seedHexToPriveKey(SEED_HEX)
  // 12D3KooWE7bA8PBbihjkATeN8hHotFjPZU9XPDn48N6qvZTVupX2
  
  let daemon = createDaemon(privateKey);

  try {
    await daemon.start();

    const version = await daemon._ipfs.version();

    print(`js-ipfs version: ${version.version}`);

    if (daemon._httpApi && daemon._httpApi._apiServers) {
      daemon._httpApi._apiServers.forEach(apiServer => {
        print(`HTTP API listening on ${apiServer.info.ma}`);
      });
    }

    if (daemon._grpcServer && daemon._grpcServer) {
      print(`gRPC listening on ${daemon._grpcServer.info.ma}`);
    }

    if (daemon._httpGateway && daemon._httpGateway._gatewayServers) {
        daemon._httpGateway._gatewayServers.forEach(gatewayServer => {
          print(`Gateway (read only) listening on ${gatewayServer.info.ma}`);
        });
      }
  
      if (daemon._httpApi && daemon._httpApi._apiServers) {
        daemon._httpApi._apiServers.forEach(apiServer => {
          print(`Web UI available at ${multiaddrToUri(apiServer.info.ma)}/webui`);
        });
      }
    } catch (/** @type {any} */ err) {
      if (err.code === 'ERR_REPO_NOT_INITIALIZED' || err.message.match(/uninitialized/i)) {
        err.message = 'no initialized ipfs repo found in ' + 'jsipfs' + '\nplease run: jsipfs init';
      }
      throw err;
    }
  
    print('Daemon is ready');

    const cleanup = async () => {
      print('Received interrupt signal, shutting down...');
      await daemon.stop();
      // await prisma.$disconnect();
      process.exit(0);
    };
  
    // listen for graceful termination
    process.on('SIGTERM', cleanup);
    process.on('SIGINT', cleanup);
    process.on('SIGHUP', cleanup);

}

startServer();

